package com.learn.thread;

/**
 * 死锁案例
 */
public class TestThreadDead {
    public static void main(String[] args) {
        MakeUp m1 = new MakeUp(0, "小红");
        MakeUp m2 = new MakeUp(1, "小美");
        m1.start();
        m2.start();
    }
}

//口红
class Lipstick {

}

//镜子
class Mirror {

}

class MakeUp extends Thread {

    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    private int choice;
    private String userName;

    public MakeUp(int choice, String userName) {
        super(userName);
        this.choice = choice;
    }

    @Override
    public void run() {
        //死锁
//        deadDemo();
        //非死锁
        dontDeadDemo();
    }

    private void deadDemo(){
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(Thread.currentThread().getName() + " 拿到口红");
                synchronized (mirror) {
                    System.out.println(Thread.currentThread().getName() + " 拿到镜子");
                }
            }
        } else {
            synchronized (mirror) {
                System.out.println(Thread.currentThread().getName() + " 拿到镜子");
                synchronized (lipstick) {
                    System.out.println(Thread.currentThread().getName() + " 拿到口红");

                }
            }
        }
    }

    private void dontDeadDemo(){
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(Thread.currentThread().getName() + " 拿到口红");

            }
            synchronized (mirror) {
                System.out.println(Thread.currentThread().getName() + " 拿到镜子");
            }
        } else {
            synchronized (mirror) {
                System.out.println(Thread.currentThread().getName() + " 拿到镜子");

            }
            synchronized (lipstick) {
                System.out.println(Thread.currentThread().getName() + " 拿到口红");

            }
        }
    }
}